<template>
  <div class="dashboard-editor-container">
    <h3>登录用户：{{ userName }}</h3>
    <div v-if="villDis" style="width:60%;margin-left: 20%;">
      <el-table :data="villTable" style="width: 100%" fit border id="tableId1">
        <el-table-column label="补贴类型" align="center" prop="type" />
        <el-table-column label="提交条数" align="center" prop="total" />
      </el-table>
    </div>
    <div v-if="townDis" style="width:80%;margin-left: 10%;">
      <el-table :data="townTable" style="width: 100%" border :loading="tableLoading" v-loading="tableLoading">
        <el-table-column label="村名称" prop="villageName" fixed align="center" />
        <el-table-column v-for="subsidy in subsidyOptions" :key="subsidy" :label="subsidy+ '数量'" :prop="subsidy+'_quantity'"
          align="center" />
      </el-table>

    </div>

    <div v-if="straDis" style="width:90%;margin-left: 5%;">
      <el-table :data="straTable" style="width: 100%" @row-click="handleTownRowClick" border :loading="tableLoading"
        v-loading="tableLoading">
        <el-table-column label="乡名称" prop="townName" width="300" align="center" />
        <el-table-column v-for="subsidy in subsidyOptions" :key="subsidy" :label="subsidy+ '数量'" :prop="subsidy+'_quantity'"
          align="center" />
      </el-table>
    </div>

    <div v-if="showVillageTable" style="margin-top: 20px;width:80%;margin-left: 10%;">
      <h3>乡：{{ selectedTown }} 下属村补贴统计</h3>
      <el-table :data="villageSubsidyData" style="width: 100%;display: block;" border :loading="villageTableLoading"
        v-loading="villageTableLoading">
        <el-table-column label="村名称" prop="villageName" fixed align="center" />
        <el-table-column v-for="subsidy in subsidyOptions" :key="subsidy" :label="subsidy+ '数量'" :prop="subsidy+'_quantity'"
          align="center" />
      </el-table>
    </div>

  </div>
</template>

<script>
import { listProduce, submitProduce, queryGroupData, queryTownRes } from "@/api/agriculture/agriculture";
import { listStrativeArea, getStrativeArea, delStrativeArea, addStrativeArea, updateStrativeArea } from "@/api/subsidy/strativeArea";
export default {
  name: "Home",
  data() {
    const now = new Date();
    return {
      straName: '',
      townName: '',
      villageName: '',
      userName: '',
      role: '',
      straDis: false, //区登陆表格
      townDis: false, //乡登陆表格
      villDis: false, //村登陆表格
      showVillageTable: false, //乡下属表格是否出现
      villageTableLoading: false, //乡下属村表格加载
      tableLoading: false, //所有村乡区表格加载
      year: now.getFullYear(), //今年
      preyear: now.getFullYear() - 1,//去年
      lastyear: now.getFullYear() - 2, //前年
      queryParams: {
        pageNum: 1,
        pageSize: 1,
        appType: '',
        straName: '',
        villageName: undefined,
        townName: undefined,
        year: now.getFullYear(),
        isprice: 1,
      },
      townOptions: [],
      villageOptions: [],
      tableData: [],
      villageSubsidyData: [], //乡下属村表格

      //区 乡 村表格
      straTable: [],
      townTable: [],
      villTable: [],
      //统计字段
      sumData: [],
      subsidyOptions: ["生产者补贴", "高油大豆补贴", "高蛋白大豆补贴", "耕地地力补贴", "耕地轮作补贴"],
    };
  },
  watch: {
  },
  created() {
    console.log("目前登录用户", this.$store.state.user.user, this.$store.state.user.roles[0])
    this.role = this.$store.state.user.roles[0];
    console.log("当前角色", this.role)
    if (this.role == 'townNongji' || this.role == 'districtNongji') {
      this.userName = this.$store.state.user.user.userName;

    }

    if (this.role == 'village') {
      console.log("村登录", this.role);
      this.villDis = true;
      this.villageName = this.$store.state.user.user.villageName;
      this.queryParams.villageName = this.villageName;
      this.userName = this.$store.state.user.user.userName;
      this.getVillList();
    }
    if (this.role == 'town') {
      console.log("乡登录", this.role)
      this.townDis = true;
      this.townName = this.$store.state.user.user.townName;
      this.userName = this.townName;
      this.queryParams.townName = this.townName;
      this.getTownList();
      // this.handleTownLogin()
    }
    if (this.role == 'district') {

      console.log("区登录", this.role);
      this.straDis = true;
      this.straName = this.$store.state.user.user.straName;
      this.queryParams.straName = this.straName;
      this.userName = this.straName;
      this.getStraList();
      // this.handleStraLogin();
    }
  },
  methods: {
    // 点击某一行乡
    async handleTownRowClick(row) {
      const townName = row.townName;
      this.selectedTown = townName;
      this.queryParams.townName = townName;
      this.queryParams.straName = ''

      this.showVillageTable = true;
      this.villageSubsidyData = [];
      this.villageTableLoading = true;

      try {
        const requests = this.subsidyOptions.map(appType => {
          const params = { ...this.queryParams, appType };
          return queryGroupData(params).then(res => ({
            appType,
            list: res || [] // 假设返回的是数组
          }));
        });

        const results = await Promise.all(requests); // results: [{ appType, list }, ...]
        console.log("当前数据",results);
        // 步骤 2：按 villageName 聚合
        const villageMap = new Map();

        results.forEach(({ appType, list }) => {
          list.forEach(item => {
            const { villageName } = item;
            if (!villageMap.has(villageName)) {
              villageMap.set(villageName, { villageName });
            }
            // 假设 quantity 字段存在；若无，可用 areaAmount 或其他字段
            villageMap.get(villageName)[`${appType}_quantity`] = item.quantity || '0';
            // 可选：保留原始对象
            // villageMap.get(villageName)[appType] = item;
          });
        });

        // 转为数组
        this.villageSubsidyData = Array.from(villageMap.values());
        console.log("所属乡的村数据111",this.villageSubsidyData)

      } catch (error) {
        console.error('获取村镇数据失败', error);
        this.$message.error('获取数据失败');
      } finally {
        this.villageTableLoading = false;
      }

    },
    
    async handleTownRowClick1(row) {
      const townName = row.townName;
      this.selectedTown = townName;
      this.showVillageTable = true;
      this.villageSubsidyData = [];
      this.villageTableLoading = true;

      try {
        // 1. 获取该乡下的村列表
        const areaRes = await listStrativeArea({ townName });
        const villages = areaRes[0]?.children?.[0]?.children || [];
        if (!villages.length) {
          this.$message.warning(`乡【${townName}】下无村数据`);
          this.villageSubsidyData = [];
          return;
        }

        // 2. 为每个村查询各类补贴 total
        const villageDataPromises = villages.map(async (village) => {
          const villageName = village.label; // 根据实际字段调整
          const rowData = { villageName };

          // 并发查询该村庄的所有补贴类型
          await Promise.all(
            this.subsidyOptions.map(async (appType) => {
              const params = {
                ...this.queryParams,
                townName: townName,
                villageName: villageName,
                appType: appType,
                // 注意：pageNum/pageSize 可能不需要，因为只关心 total
              };
              try {
                const res = await listProduce(params);
                rowData[appType] = res.total || 0;
              } catch (err) {
                console.warn(`查询失败: ${townName} - ${villageName} - ${appType}`, err);
                rowData[appType] = 0;
              }
            })
          );
          return rowData;
        });

        const villageStats = await Promise.all(villageDataPromises);
        this.villageSubsidyData = villageStats;
      } catch (error) {
        console.error('加载村级数据失败:', error);
        this.$message.error('加载村级补贴数据失败');
      } finally {
        this.villageTableLoading = false;
      }
    },

    async handleStraLogin() {
      this.straName = this.$store.state.user.user.straName;
      this.queryParams.straName = this.straName;
      this.userName = this.straName;

      // 先获取村列表
      try {
        const response = await listStrativeArea({ departmentName: this.straName });
        // 假设结构是 response[0].children[0].children 是村数组
        this.townOptions = response[0].children;
        console.log("xiang", this.townOptions)
        if (!this.townOptions.length) {
          this.$message.warning('未获取到村数据');
          return;
        }

        // 开始统计每个村的各类补贴
        await this.loadTownSubsidyStats();
      } catch (error) {
        console.error('获取乡列表失败:', error);
        this.$message.error('获取乡列表失败');
      }
    },

    async loadTownSubsidyStats() {
      this.tableLoading = true;
      this.straTable = [];

      // 构建所有请求：每个村 × 每种补贴
      const allPromises = [];

      for (const town of this.townOptions) {
        const townName = town.label; // 假设村名在 label 字段
        console.log("乡", townName)
        const row = { townName }; // 表格行对象

        // 为当前村，对每种补贴发起请求
        const subsidyPromises = this.subsidyOptions.map(appType => {
          const params = {
            ...this.queryParams,
            straName: this.straName,
            townName: townName,
            appType: appType,
          };

          return listProduce(params)
            .then(res => {
              row[appType] = res.total || 0;
            })
            .catch(err => {
              console.warn(`乡【${townName}】补贴【${appType}】查询失败:`, err);
              row[appType] = 0;
            });
        });

        // 等待当前村的所有补贴请求完成
        await Promise.all(subsidyPromises);
        allPromises.push(row); // 收集整行数据
      }

      // 所有村处理完毕
      this.straTable = allPromises;
      this.tableLoading = false;
      console.log('最终表格数据:', this.straTable);
    },


    async handleTownLogin() {
      this.townDis = true;
      this.townName = this.$store.state.user.user.townName;
      this.userName = this.townName;
      this.queryParams.townName = this.townName;

      // 先获取村列表
      try {
        const response = await listStrativeArea({ townName: this.townName });
        // 假设结构是 response[0].children[0].children 是村数组
        this.villageOptions = response[0]?.children?.[0]?.children || [];
        if (!this.villageOptions.length) {
          this.$message.warning('未获取到村数据');
          return;
        }

        // 开始统计每个村的各类补贴
        await this.loadVillageSubsidyStats();
      } catch (error) {
        console.error('获取村列表失败:', error);
        this.$message.error('获取村列表失败');
      }
    },

    async loadVillageSubsidyStats() {
      this.tableLoading = true;
      this.townTable = [];

      // 构建所有请求：每个村 × 每种补贴
      const allPromises = [];

      for (const village of this.villageOptions) {
        const villageName = village.label; // 假设村名在 label 字段
        const row = { villageName }; // 表格行对象

        // 为当前村，对每种补贴发起请求
        const subsidyPromises = this.subsidyOptions.map(appType => {
          const params = {
            ...this.queryParams,
            townName: this.townName,
            villageName: villageName,
            appType: appType,
          };

          return listProduce(params)
            .then(res => {
              row[appType] = res.total || 0;
            })
            .catch(err => {
              console.warn(`村【${villageName}】补贴【${appType}】查询失败:`, err);
              row[appType] = 0;
            });
        });

        // 等待当前村的所有补贴请求完成
        await Promise.all(subsidyPromises);
        allPromises.push(row); // 收集整行数据
      }

      // 所有村处理完毕
      this.townTable = allPromises;
      this.tableLoading = false;
      console.log('最终表格数据:', this.townTable);
    },

    async getStraList() {
      this.tableLoading = true;
      try {
        const requests = this.subsidyOptions.map(appType => {
          const params = { ...this.queryParams, appType };
          return queryGroupData(params).then(res => ({
            appType,
            list: res || [] // 假设返回的是数组
          }));
        });

        const results = await Promise.all(requests); // results: [{ appType, list }, ...]
        console.log("当前数据",results);
        // 步骤 2：按 villageName 聚合
        const townMap = new Map();

        results.forEach(({ appType, list }) => {
          list.forEach(item => {
            const { townName } = item;
            if (!townMap.has(townName)) {
              townMap.set(townName, { townName });
            }
            // 假设 quantity 字段存在；若无，可用 areaAmount 或其他字段
            townMap.get(townName)[`${appType}_quantity`] = item.quantity || '0';
            // 可选：保留原始对象
            // townMap.get(townName)[appType] = item;
          });
        });

        // 转为数组
        this.straTable = Array.from(townMap.values());
        console.log("乡表格",this.townTable)

      } catch (error) {
        console.error('获取乡数据失败', error);
        this.$message.error('获取数据失败');
      } finally {
        this.tableLoading = false;
      }
    },

    async getTownList() {
      this.tableLoading = true;
      try {
        const requests = this.subsidyOptions.map(appType => {
          const params = { ...this.queryParams, appType };
          return queryGroupData(params).then(res => ({
            appType,
            list: res || [] // 假设返回的是数组
          }));
        });

        const results = await Promise.all(requests); // results: [{ appType, list }, ...]
        console.log("当前数据",results);
        // 步骤 2：按 villageName 聚合
        const villageMap = new Map();

        results.forEach(({ appType, list }) => {
          list.forEach(item => {
            const { villageName } = item;
            if (!villageMap.has(villageName)) {
              villageMap.set(villageName, { villageName });
            }
            // 假设 quantity 字段存在；若无，可用 areaAmount 或其他字段
            villageMap.get(villageName)[`${appType}_quantity`] = item.quantity || '0';
            // 可选：保留原始对象
            // villageMap.get(villageName)[appType] = item;
          });
        });

        // 转为数组
        this.townTable = Array.from(villageMap.values());
        console.log("乡表格",this.townTable)

      } catch (error) {
        console.error('获取村镇数据失败', error);
        this.$message.error('获取数据失败');
      } finally {
        this.tableLoading = false;
      }
    },

    async getVillList() {
      this.tableLoading = true;
      this.villTable = []; // 清空旧数据
      // 构建所有请求的 Promise 数组
      const requests = this.subsidyOptions.map(appType => {
        const params = { ...this.queryParams, appType }; // 深拷贝基本参数并覆盖 appType
        return listProduce(params).then(response => {
          return {
            type: appType,         // 表格中“单位名称”列显示补贴类型
            total: response.total || 0 // 确保有默认值
          };
        }).catch(err => {
          console.error(`获取 ${appType} 数据失败:`, err);
          return { type: appType, total: 0 }; // 失败也返回 0，避免中断
        });
      });

      try {
        const results = await Promise.all(requests);
        this.villTable = results;
        console.log("汇总数据:", this.villTable);
      } finally {
        this.tableLoading = false;
      }
    },

  }
};

</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

::v-deep .el-table--border .el-table__cell {
  // border-color: black !important;
  padding: 6px 0;
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
